package com.itrip.listener;

import com.itrip.service.OrderService;
import com.itrip.service.TempStoreService;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    @Resource
    private OrderService orderService;

    @Resource
    private TempStoreService tempStoreService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        //获取失效的key
        String expiredKey = message.toString();
        if (expiredKey.startsWith("order:")){
            String id = expiredKey.substring(expiredKey.indexOf(":") + 1, expiredKey.indexOf(","));
            long orderId = Long.parseLong(id);
            int status = orderService.getOrderStatus(orderId);
            if (status == 0){
                int countOrder = orderService.updateOrderStatusInvalid(orderId);
                String storeStr = expiredKey.substring(expiredKey.lastIndexOf(",") + 1);
                int store = Integer.parseInt(storeStr);
                String roomStr = expiredKey.substring(expiredKey.indexOf(",") + 1, expiredKey.lastIndexOf(","));
                long roomId = Long.parseLong(roomStr);
                int countStore = tempStoreService.addStoreRevert(roomId,store);
            }
        }

    }

}
